package utils;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.UUID;

import client.Callback_deprecated;
import client.CallbackHandler;
import client.ICallbackHandler;
import pt.iscte.dcti.pa.controller.WorksheetController;
import pt.iscte.dcti.pa.model.WorksheetModel;

public class SingletonRmiWrapper {
	//ATTRIBUTES
	private server.ICallbackHandler proxy;
	private static SingletonRmiWrapper wrapper;
	private UUID uniqueId;
	private WorksheetController ctrler;
	private boolean offline;
	
	//CONSTUCTORS
	private SingletonRmiWrapper(WorksheetController _controller) {
		
		this.ctrler = _controller;
		System.setProperty("java.security.policy", "java.policy");
		String hostName = "tcm-lptp"; 
		  //"192.168.1.66";
		String portNum = "1099";
		uniqueId = java.util.UUID.randomUUID();
		
		this.offline = true;
		
		String registryUrl = String.format("rmi://%s:%s/eexcel", hostName, portNum);
		try {
			proxy = (server.ICallbackHandler) Naming .lookup(registryUrl);
			//clientIpAndPort = Common.getMatches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}:\\d+", this.proxy.toString()).get(0);
			System.out.println(proxy.toString());
			System.out.println("Lookup completed");
			// System.out.println("Server said" + h.);
			ICallbackHandler callbackObj = new CallbackHandler(this.ctrler);
			proxy.registerForCallback(callbackObj, uniqueId);
			System.out.println("Registed for callback");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (RemoteException e) {		
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static synchronized SingletonRmiWrapper getWrapper() {
		
		return wrapper;
	}
	
	public static synchronized SingletonRmiWrapper getWrapper(WorksheetController _ctrler) {
		
		if (wrapper == null) {
			wrapper = new SingletonRmiWrapper(_ctrler);
		}
		return wrapper;
	}
	
	public boolean lockCell(int abscissa, int ordinate) {
		try {
			return proxy.lockCell(abscissa, ordinate, uniqueId);
		} catch (RemoteException e) {
			System.out.println("An exception was throwned @RmiWrapper.lockCell");
			//TODO tratar excepcao
			return false;
		}
	}
	
	public String getPrecedentOperationResult(String expression) {
		try {
			return proxy.getPrecedentOperationResult(expression, uniqueId);
		} catch (RemoteException e) {
			System.out.println("An exception was throwned @RmiWrapper.getPrecedentOperationResult");
			//TODO tratar excepcao
			return null;
		}
	}
	
	public void updateColaboratorsCell(String value) {
		
		try {
			
			proxy.updateColaboratorsCell(this.uniqueId, value);
			
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
